<?php

/**
 * 留言管理
 * @author huuwhois
 * @time 2017/11/17
 */
namespace app\admin\controller;

use app\admin\model\Review as ReviewModel;
use think\Request;

class Review extends Base
{
    protected $model;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->model = new ReviewModel();
    }

    public function index()
    {
        $map = [];
        $counts_page = 8;
        $counts = $this->model->where($map)->count('id');
        $pages = intval(ceil($counts / $counts_page));

        $data = $this->model->where($map)
            ->order('id', 'desc')
            ->paginate($counts_page);

        // echo json_encode($data);
        // exit;
        $this->assign('counts', $counts);
        $this->assign('pages', $pages);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function discuss()
    {
        if (Request::instance()->isAjax()) {
            $param = input('post.');
            $param['time'] = time();
            // var_dump($param);
            // exit();
            try {
                $this->model->save($param);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }

            $param['id'] = $this->model->id;
            $param['time'] = date("Y-m-d H:i:s", $param['time']);
            return ['code' => 2, 'data' => $param];
        }
        $data = $this->model->where('status', 1)->where('pid', 0)->order('id desc')->paginate(6);

        foreach ($data as &$val) {
            $id = $val->id;
            $val->child = $this->model->where('status', 1)->where('pid', $id)->select();
        }
        // $data = [];
        // return json_encode($data);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function complain($id)
    {
        $complain = $this->model->where('id', $id)->value('complain');
        
        $res = $this->model->save(['complain' => $complain + 1], ['id' => $id]);

        if ($res !== false) {
            return ['code'=>2];
        } else {
            return ['code'=>0];
        }
    }
}
